<?php
/**
 * Created by Jayli.
 * User: Administrator
 * Date: 2018-03-07
 * Time: 14:46
 */

namespace App\Http\Controllers\Web\Member\Buyer;

use App\Http\Controllers\Web\BaseController;
use App\Services\Cookie\Carts;
use Illuminate\Http\Request;

class OrdersController extends BaseController
{
    protected $api_url = [
        'index' => ['get', 'buyer/orders'],
        'show' => ['get', 'buyer/orders/%d'],
        'store' => ['post', 'buyer/orders'],
        'update' => ['put', 'buyer/orders/%d'],
        'delete' => ['delete', ''],
        'address_index' => ['get', 'buyer/address'],
        'invoices_index' => ['get', 'buyer/invoices'],
        'skus_index' => ['get', 'buyer/skus'],
        'skus_show' => ['get', 'buyer/skus/%d'],
        'show_express' => ['get', 'buyer/orders/%d/order_express/0'],
        'company_show' => ['get', 'shop/company_show/%d'],
    ];

    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function index()
    {
        //参数部分
        $search_params = $this->request->all(['order_code', 'order_status', 'order_at']);
        $page = $this->request->get('page', 1);
        $params = [
            'search' => search_params($search_params),
            'searchJoin' => 'and',
            'page' => $page,
            'with' => 'orderProducts;shop;items_products;items_information',
            'orderBy'=>'id',
            'sortedBy'=>'desc',
        ];

        //请求部分
        $ret = http_web($this->api_url['index'])->send($params);

        //结果处理部分
        $data = paginate($this->request, $ret['data']);

        foreach($data['list'] as $k=>$v){
            if(!empty($v['items_information'])){
                $data['list'][$k]['items_information']['quote_contain']=\GuzzleHttp\json_decode($v['items_information']['quote_contain'],true);
            }
        }
        //回填搜索框值
        $data['search_params'] = $search_params;
//        dd($data);
        return view('web.user.buyer.order_list', $data);
    }

    public function show($id)
    {
        //参数部分
        $params = [
            'with' => 'shop;orderProducts;invoice;items_products;items_information'
        ];

        //请求部分
        $ret = http_web($this->api_url['show'], [$id])->send($params);
        if(isset($ret['data']['shop']['sp_cmp_id'])){
            $company_id=$ret['data']['shop']['sp_cmp_id'];
            $company = http_web($this->api_url['company_show'], [$company_id])->send();
            $ret['data']['company']=$company['data'];
        }else{
            $ret['data']['company']=[];
        }

        if(!empty($ret['data']['items_information'])){
            $ret['data']['items_information']['quote_contain']=\GuzzleHttp\json_decode($ret['data']['items_information']['quote_contain'],true);
        }
        $express_ret = http_web($this->api_url['show_express'], [$id])->auto(false)->send();

        $express = $express_ret['code'] == 0 ? $express_ret['data'] : [];
        if (isset($express['data'])){
            $express = $express['data'];
        }
        return view('web.user.buyer.order_track', ['order' => $ret['data'], 'express' => $express]);
    }

    public function create()
    {
        $this->validate($this->request, [
            'type' => 'required|in:cart,direct',
            'sku_id' => 'required_if:type,direct',
            'sku_num' => 'required_if:type,direct',
            'product_data' => 'required_if:type,cart|array',
        ],[
            'product_data.required_if'=>'没有选择任何商品'
        ]);
        $data = $this->request->all(['type', 'sku_id', 'sku_num', 'product_data']);

        if($data['type'] == 'cart'){
            $sku_num = [];
            foreach($data['product_data'] as $item){
                if(array_get($item, 'check')){
                    $sku_num[$item['sku_id']] = $item['num'];
                }
            }
            //请求部分-购物车
            $skus = http_web($this->api_url['skus_index'])->send(['sku_num' => $sku_num]);
        }else{
            //请求部分-直接下单
            $skus = http_web($this->api_url['skus_show'], [$data['sku_id']])->send(['sku_num' => $data['sku_num'] ]);
        }

        //商品库存不足
        if($skus['code'] == 1242){
            return redirect()->back();
        }
        //存在自己店铺产品
        if($skus['code'] == 1244){
            return redirect()->back()->withErrors(['不能购买自己店铺产品！']);
        }

        //请求部分-地址
        $address = http_web($this->api_url['address_index'])->send(['type' => 'all']);

        if(!($skus['http_code'] == 200 && $skus['code'] == 0)){
            //@todo
            //return ;
        }

        //请求部分-发票
        $invoices = http_web($this->api_url['invoices_index'])->send(['type' => 'all']);

        if(!($skus['http_code'] == 200 && $skus['code'] == 0)){
            //@todo
            //return ;
        }

        $default_invoice = null;
        foreach($invoices['data'] as $invoice){
            if($invoice['is_default'] == 1){
                $default_invoice = $invoice;
            }
        }

        $ret = [
            'shops' => $skus['data'],
            'address' => $address['data'],
            'default_invoice' => $default_invoice
        ];

        return view('web.order.submit_cart', $ret);
    }

    public function store(Carts $carts_service)
    {
        $this->validate($this->request, [
            'address_id' => 'required|integer',
            'sku_num' => 'required|array',
            'invoices' => 'required|array',
            'remark' => 'required|array'
        ]);

        //参数部分
        $params = $this->request->all(['address_id', 'sku_num', 'invoices', 'remark']);

//        dd($params);
        //请求部分
        $ret = http_web($this->api_url['store'])->send($params);

        if($ret['code'] == 0){
            $carts_service->fresh_get();
            //跳转支付页
            $order_codes = implode(',', $ret['data']['order_codes']);
            return redirect('/member/buyer/pay?order_codes=' . $order_codes);
        }

        //结果处理部分
        return redirect()->back();
    }

    public function update($id)
    {
        $this->validate($this->request, [
            'order_status' => 'required|in:4,5'
        ]);
        $data = $this->request->all(['order_status']);

        //请求部分
        $ret = http_web($this->api_url['update'], [$id])->send($data);
        return $ret;
    }

    public function comments($order_id)
    {
        //参数部分
        $params = [
            'with' => 'orderProducts'
        ];

        //请求部分
        $ret = http_web($this->api_url['show'], [$order_id])->send($params);

        //结果处理部分
        $order_products = array_get($ret, 'data.order_products', []);

        return view('web.user.buyer.comment', ['order_products' => $order_products]);
    }

    public function showOrderExpress($order_id)
    {
        $ret = http_web($this->api_url['show_express'], [$order_id])->send();

        return view('web.common.logistics_info', ['express' => $ret['data']]);
    }
    /**
     * ajax 检测商品是否可以 立即购买
     * */
    public function checkBuyProduct($sku_id)
    {
        $sku_num = $this->request->get('sku_num',1);
        //请求部分-直接下单
        $skus = http_web($this->api_url['skus_show'], [$sku_id])->send(['sku_num' => $sku_num]);
        $msg  = '';
        //商品库存不足
        if($skus['code'] == 1242){
            $msg = '商品库存不足！';
        }
        //存在自己店铺产品
        if($skus['code'] == 1244){
            $msg = '不能购买自己店铺产品！';
        }

        return response()->json(['code'=>$skus['code'],'message'=>$msg]);
    }
}